// pages/testdetail/testdetail.js
import { getAssessmentQuestions } from '../../api/testdetail'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentQuestion: 1,
    totalQuestions: 0,
    progressPercentage: 0, // 第一题进度20%
    selectedAnswer: null,
    currentQuestionData: {},
    questions: [],
    userAnswers: [],
    assessmentId: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id) {
      this.setData({
        assessmentId: options.id
      })
      this.loadAssessmentData(options.id)
    } else {
      wx.showToast({
        title: '测评ID不存在',
        icon: 'error',
        duration: 2000
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 2000)
    }
  },
    // 加载测评数据
    async loadAssessmentData(assessmentId) {
      try {
        wx.showLoading({
          title: '加载题目中...',
        })
  
        const questions = await getAssessmentQuestions(assessmentId)
        
        this.setData({
          questions: questions,
          totalQuestions: questions.length,
          currentQuestionData: questions[0],
          progressPercentage: questions.length > 0 ? (1 / questions.length) * 100 : 0
        })
  
        wx.hideLoading()
      } catch (error) {
        console.error('加载测评数据失败:', error)
        wx.hideLoading()
        wx.showToast({
          title: '加载失败，请重试',
          icon: 'error',
          duration: 2000
        })
        
        // 加载失败时返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 2000)
      }
    },

    // 选择选项
    selectOption: function(e) {
      const index = e.currentTarget.dataset.index;
      this.setData({
        selectedAnswer: index
      });
    },
      // 上一题
    goToPrevQuestion: function() {
      if (this.data.currentQuestion <= 1) return;

      const prevQuestionIndex = this.data.currentQuestion - 2; // 数组索引从0开始
      const prevProgress = Math.round(((this.data.currentQuestion - 1) / this.data.totalQuestions) * 100);

      // 获取上一题的答案（如果有）
      const prevAnswer = this.data.userAnswers[this.data.currentQuestion - 2];
      
      this.setData({
        currentQuestion: this.data.currentQuestion - 1,
        progressPercentage: prevProgress,
        selectedAnswer: prevAnswer ? prevAnswer.answerIndex : null,
        currentQuestionData: this.data.questions[prevQuestionIndex]
      });
    },
  // 下一题/完成测试
  goToNextQuestion: function() {
    if (this.data.selectedAnswer === null) {
      wx.showToast({
        title: '请选择答案',
        icon: 'none'
      })
      return;
    }
    // 保存当前答案
    const currentAnswer = {
      questionId: this.data.currentQuestionData.id,
      answerIndex: this.data.selectedAnswer,
      answerText: this.data.currentQuestionData.options[this.data.selectedAnswer].text,
      answerValue: this.data.currentQuestionData.options[this.data.selectedAnswer].value
    };
    let userAnswers = this.data.userAnswers;
    
    // 如果已经答过这题，更新答案；否则新增
    const existingAnswerIndex = userAnswers.findIndex(item => item.questionId === currentAnswer.questionId);
    if (existingAnswerIndex !== -1) {
      userAnswers[existingAnswerIndex] = currentAnswer;
    } else {
      userAnswers.push(currentAnswer);
    }
    
    // 如果是最后一题，完成测试
    if (this.data.currentQuestion === this.data.totalQuestions) {
      this.completeTest(userAnswers);
      return;
    }

    // 切换到下一题
    const nextQuestionIndex = this.data.currentQuestion;
    const nextProgress = Math.round(((nextQuestionIndex + 1) / this.data.totalQuestions) * 100);

    // 获取下一题的答案（如果有）
    const nextAnswer = userAnswers.find(item => item.questionId === this.data.questions[nextQuestionIndex].id);

    this.setData({
      currentQuestion: nextQuestionIndex + 1,
      progressPercentage: nextProgress,
      selectedAnswer: nextAnswer ? nextAnswer.answerIndex : null,
      currentQuestionData: this.data.questions[nextQuestionIndex],
      userAnswers: userAnswers
    });
  },
  
  // 完成测试
  completeTest: function(userAnswers) {
    console.log('测试完成，用户答案：', userAnswers);
    // 这里可以跳转到结果页面或调用接口
    wx.showToast({
      title: '测试完成！',
      icon: 'success',
      duration: 2000,
      success: () => {
        setTimeout(() => {
          // 跳转到结果页面，传递答案数据和测评ID
          wx.navigateTo({
            url: `/pages/testdetail/testresult/testresult?answers=${encodeURIComponent(JSON.stringify(userAnswers))}&assessmentId=${this.data.assessmentId}`
          });
        }, 2000);
      }
    });
  },
  // 返回测试页面
  gobackTest:function() {
    wx.navigateBack({
      dalta:1
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})